package com.example.mp3player01;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;

import com.example.download.HttpDownloader;
import com.example.model.Mp3Info;
import com.example.xml.Mp3ListContentHandler;

public class Mp3ListActivity extends ListActivity {
	


	private static final int UPDATE = 1;
	private static final int ABOUT = 2;
	
	private Context context = this;
	
	private List<Mp3Info> mp3Infos;
	
	// the following url points to localhost called from emulator
	private static final String urlStr = "http://10.0.2.2:8080/mp3/resources.xml";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.remote_mp3_list);
		
		// turn the check off
		StrictMode.ThreadPolicy policy = new StrictMode.
		ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy); 
		
		updateListView();
	}

	
	
	private void updateListView() {
		String xml = downloadXML(urlStr);
		mp3Infos = parse(xml);
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		for (Iterator it = mp3Infos.iterator(); it.hasNext();) {
			Mp3Info mp3Info = (Mp3Info) it.next();
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("mp3_name", mp3Info.getMp3Name());
			map.put("mp3_size", mp3Info.getMp3Size());
			list.add(map);
		}
		
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.mp3info_item, new String[] {"mp3_name", "mp3_size"}
				, new int[] {R.id.mp3_name, R.id.mp3_size});
		setListAdapter(simpleAdapter);
	}
	
	private String downloadXML(String urlStr) {
		HttpDownloader httpDownloader = new HttpDownloader();
		String result = httpDownloader.download(urlStr);
		return result;
		
	}
	
	private List<Mp3Info> parse(String xmlStr) {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		List<Mp3Info> infos = null;
		try {
			XMLReader xmlReader = factory.newSAXParser().getXMLReader();
			infos = new ArrayList<Mp3Info>();
			Mp3ListContentHandler mp3ListContentHandler = new Mp3ListContentHandler(infos);
			xmlReader.setContentHandler(mp3ListContentHandler);
			xmlReader.parse(new InputSource(new StringReader(xmlStr)));
			
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		
		return infos;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Mp3Info mp3Info = mp3Infos.get(position);
		
//		Intent intent = new Intent();
//		intent.putExtra("mp3Info", mp3Info);
//		intent.setClass(this, DownloadService.class);
//		startService(intent);
		DownloadMP3Task task = new DownloadMP3Task();
	    task.execute(new String[] {mp3Info.getMp3Name()});
		
	}
	
	private class DownloadMP3Task extends AsyncTask<String, Void, String> {
		
	    @Override
	    protected String doInBackground(String... urls) {
	      String mp3Name = urls[0];
	      String mp3Url = "http://10.0.2.2:8080/mp3/" + mp3Name;
			HttpDownloader downloader = new HttpDownloader();
			int result = downloader.downFile(mp3Url, "mp3/", mp3Name);
			
			String resultMessage = null;
			if (result == -1) {
				resultMessage = "download failed.";
			} else if (result == 0) {
				resultMessage = "File is already downloaded.";
			} else if (result == 1) {
				resultMessage = "download successfully.";
			} 
	      
	      return resultMessage;
	    }

		@Override
	    protected void onPostExecute(String result) {
//	      textView.setText(result);
	      popAlert(result);
	    }
	    
	    private void popAlert(String result) {
		    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
			    
			// set dialog message
			alertDialogBuilder
				.setMessage(result)
				.setCancelable(false)
				.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
							
					}
				});
	 
			// create alert dialog
			AlertDialog alertDialog = alertDialogBuilder.create();
 
			// show it
			alertDialog.show();
		}
	}
	

	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		menu.add(0, UPDATE, 1, R.string.mp3list_update);
		menu.add(0, ABOUT, 2, R.string.mp3list_about);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == UPDATE) {
			updateListView();
		} else if (item.getItemId() == ABOUT) {
			
			
		}
		
		return super.onOptionsItemSelected(item);
	}

}
